﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Zero.UControl.Component.ScreenCut
{
    /// <summary>
    /// ResizableSelectionBox.xaml 的交互逻辑
    /// </summary>
    public partial class ResizableSelectionBox : UserControl
    {
        private Point _dragStart;
        private string _draggingHandle = null;
        private const double MinWidth = 20;
        private const double MinHeight = 20;
        private const double MinGap = 20;
        private const double MinDelta = 0.5;

        public ResizableSelectionBox()
        {
            InitializeComponent();
            Loaded += UpdateHandles;
            SizeChanged += SizeChange;

            foreach (var handle in new[] { TopLeft, TopCenter, TopRight, MiddleRight, BottomRight, BottomCenter, BottomLeft, MiddleLeft })
            {
                handle.MouseLeftButtonDown += Handle_MouseLeftButtonDown;
                handle.MouseMove += Handle_MouseMove;
                handle.MouseLeftButtonUp += Handle_MouseLeftButtonUp;
            }
        }

        private bool showBorder;

        public bool ShowBorder
        {
            get { return showBorder; }
            set 
            { 
                showBorder = value;
                if (value)
                {
                    SelectionRect.Stroke = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4d90fe"));
                    ShowStretchNode = Visibility.Visible;
                }
                else
                {
                    SelectionRect.Stroke = new SolidColorBrush(Colors.Transparent);
                    ShowStretchNode = Visibility.Collapsed;
                }
            }
        }


        public Visibility ShowStretchNode
        {
            get { return (Visibility)GetValue(ShowStretchNodeProperty); }
            set { SetValue(ShowStretchNodeProperty, value); }
        }

        public static readonly DependencyProperty ShowStretchNodeProperty =
            DependencyProperty.Register("ShowStretchNode", typeof(Visibility), typeof(ResizableSelectionBox), new PropertyMetadata(Visibility.Visible));


        private void Handle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (sender is Ellipse handle)
            {
                _draggingHandle = handle.Name;
                _dragStart = e.GetPosition(Parent as UIElement);
                handle.CaptureMouse();
                e.Handled = true;
            }
        }

        private void Handle_MouseMove(object sender, MouseEventArgs e)
        {
            if (_draggingHandle == null || e.LeftButton != MouseButtonState.Pressed)
                return;

            Point current = e.GetPosition(Parent as UIElement);
            double offsetX = current.X - _dragStart.X;
            double offsetY = current.Y - _dragStart.Y;
            if (Math.Abs(offsetX) < MinDelta && Math.Abs(offsetY) < MinDelta)
                return;

            var left = Canvas.GetLeft(this);
            var top = Canvas.GetTop(this);
            var width = this.ActualWidth;
            var height = this.ActualHeight;
            var right = left + width;
            var bottom = top + height;

            switch (_draggingHandle)
            {
                case "TopLeft":
                    left += offsetX;
                    width -= offsetX;
                    top += offsetY;
                    height -= offsetY;
                    break;
                case "TopCenter":
                    top += offsetY;
                    height -= offsetY;
                    break;
                case "TopRight":
                    width += offsetX;
                    top += offsetY;
                    height -= offsetY;
                    break;
                case "MiddleRight":
                    width += offsetX;
                    break;
                case "BottomRight":
                    width += offsetX;
                    height += offsetY;
                    break;
                case "BottomCenter":
                    height += offsetY;
                    break;
                case "BottomLeft":
                    left += offsetX;
                    width -= offsetX;
                    height += offsetY;
                    break;
                case "MiddleLeft":
                    left += offsetX;
                    width -= offsetX;
                    break;
            }

            // 限制最小值
            width = Math.Max(width, MinWidth);
            height = Math.Max(height, MinHeight);

            left = Math.Min(left, right - MinGap);
            top = Math.Min(top, bottom - MinGap);

            Canvas.SetLeft(this, left);
            Canvas.SetTop(this, top);
            this.Width = width;
            this.Height = height;

            _dragStart = current;
            UpdateLayoutAndHandles();
        }

        private void Handle_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _draggingHandle = null;
            if (sender is Ellipse handle)
                handle.ReleaseMouseCapture();
        }

        private void UpdateLayoutAndHandles()
        {
            // 更新中间矩形
            Canvas.SetLeft(SelectionRect, 0);
            Canvas.SetTop(SelectionRect, 0);
            SelectionRect.Width = ActualWidth;
            SelectionRect.Height = ActualHeight;

            double cx = ActualWidth / 2;
            double cy = ActualHeight / 2;

            // 设置控制点位置（相对控件自身）
            SetHandle(TopLeft, 0, 0);
            SetHandle(TopCenter, cx, 0);
            SetHandle(TopRight, ActualWidth, 0);
            SetHandle(MiddleRight, ActualWidth, cy);
            SetHandle(BottomRight, ActualWidth, ActualHeight);
            SetHandle(BottomCenter, cx, ActualHeight);
            SetHandle(BottomLeft, 0, ActualHeight);
            SetHandle(MiddleLeft, 0, cy);
        }

        private void SetHandle(Ellipse handle, double x, double y)
        {
            Canvas.SetLeft(handle, x - handle.ActualWidth / 2);
            Canvas.SetTop(handle, y - handle.ActualHeight / 2);
        }

        private void SizeChange(object sender, SizeChangedEventArgs e)
        {
            UpdateLayoutAndHandles();
        }

        private void UpdateHandles(object sender, RoutedEventArgs e)
        {
            double w = ActualWidth;
            double h = ActualHeight;

            Canvas.SetLeft(TopLeft, -5);
            Canvas.SetTop(TopLeft, -5);

            Canvas.SetLeft(TopCenter, w / 2 - 5);
            Canvas.SetTop(TopCenter, -5);

            Canvas.SetLeft(TopRight, w - 5);
            Canvas.SetTop(TopRight, -5);

            Canvas.SetLeft(MiddleRight, w - 5);
            Canvas.SetTop(MiddleRight, h / 2 - 5);

            Canvas.SetLeft(BottomRight, w - 5);
            Canvas.SetTop(BottomRight, h - 5);

            Canvas.SetLeft(BottomCenter, w / 2 - 5);
            Canvas.SetTop(BottomCenter, h - 5);

            Canvas.SetLeft(BottomLeft, -5);
            Canvas.SetTop(BottomLeft, h - 5);

            Canvas.SetLeft(MiddleLeft, -5);
            Canvas.SetTop(MiddleLeft, h / 2 - 5);
        }
    }
}
